package lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class TestReadWriteLock {

    private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();
    // 读锁 非阻塞
    private static final ReentrantReadWriteLock.ReadLock READ_LOCK = LOCK.readLock();
    // 写锁 阻塞
    private static final ReentrantReadWriteLock.WriteLock WRITE_LOCK = LOCK.writeLock();

    private static void read(){
        READ_LOCK.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"获取读锁");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            System.out.println(Thread.currentThread().getName()+"释放读锁");
            READ_LOCK.unlock();
        }
    }

    private static void write(){
        WRITE_LOCK.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"获取写锁");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            System.out.println(Thread.currentThread().getName()+"释放写锁");
            WRITE_LOCK.unlock();
        }
    }


    public static void main(String[] args) {
        new Thread(() -> read(),"Thread1").start();
        new Thread(() -> read(),"Thread2").start();
        new Thread(() -> write(),"Thread3").start();
        new Thread(() -> write(),"Thread4").start();
    }
}
